package at.fhj.swd.pse.helper;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.NoResultException;

import org.apache.commons.lang3.StringUtils;
import org.jboss.logging.Logger;

import at.fhj.swd.pse.beans.LoginBean;

@Model
public class LoginHelper {

	private static final Logger logger = Logger.getLogger(LoginHelper.class);
	public static String LOGIN = "loginpage:";
	@Inject
	private LoginBean loginBean;

	@Named
	private String username;

	@Named
	private String password;

	@PostConstruct
	public void init() {
		logger.info("init LoginHelper");

	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(final String password) {
		this.password = password;
	}

	private boolean validateInput(final FacesContext context) {
		boolean isValid = true;

		if (StringUtils.isBlank(this.getUsername())) {
			FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please enter a username!", "Please enter a username!");
			context.addMessage(LOGIN + "username", m);
			isValid = false;
		}
		if (StringUtils.isBlank(this.getPassword())) {
			FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please enter a password!", "Please enter a password!");
			context.addMessage(LOGIN + "password", m);
			isValid = false;
		}

		return isValid;
	}

	public void login(final ActionEvent actionEvent) {
		FacesContext context = FacesContext.getCurrentInstance();

		// Search for existing user in DB
		boolean loggedIn = false;
		String errorDetail = null;
		boolean isValid = this.validateInput(context);

		if (isValid) {
			try {
				loggedIn = this.loginBean.loginWithCredentials(this.getUsername(), this.getPassword());
			} catch (IllegalArgumentException ex) {

				if (ex.getMessage() == "username") {
					errorDetail = "No username entered";
				}
				if (ex.getMessage() == "password") {
					errorDetail = "No password entered";
				}
			} catch (NoResultException ex) {
				errorDetail = "Invalid credentials";
			} catch (Exception ex) {
				logger.error(ex.getMessage(), ex);
			}

			// Show Result
			if (loggedIn) {
				ExternalContext ec = context.getExternalContext();
				try {
					ec.redirect(ec.getRequestContextPath());
				} catch (IOException e) {
					context.addMessage(LOGIN + "loginButton", new FacesMessage("Login successful."));
					return;
				}
			} else {
				String message = "Login failed";
				if (errorDetail != null) {
					message += ": " + errorDetail;
				}
				context.addMessage(LOGIN + "loginButton", new FacesMessage(FacesMessage.SEVERITY_WARN, message, null));
			}
		}
	}

	public void logout() {
		this.loginBean.logout();
	}
}
